package middleware

import (
	"github.com/gin-gonic/gin"
	"reggie/common"
)

func AuthWithLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获得uri
		uri := c.Request.RequestURI		//-> /v1/employee/login
		//fmt.Println("uri = ", uri)

		// 获取baseContext的id
		id := common.GetBaseContext()
		//fmt.Println("id = ", id, ",     ", len(id))

		// 获取cookie的id
		// 获取客户端是否携带cookie
		cookieId, _ := c.Cookie("id")  // 这里不要接收err，google的bug：https://ask.csdn.net/questions/1010949

		//fmt.Println("cookieId = ", cookieId, ",   ", len(cookieId))

		// 放行策略 和 重定向
		var waiteList = []string{"/v1/employee/login"}
		if uri == waiteList[0] {
			//fmt.Println("登陆login过来的")
			c.Next()
		} else if len(id) != 0 && len(cookieId) != 0 && id == cookieId {
			//fmt.Println("登陆过了，也有cookie")
			c.Next()
		} else {
			//fmt.Println("---->>>>> 没授权")
			c.Abort()
			//c.String(401, "fail")
			c.JSON(401, gin.H{
				"data": nil,
				"msg": "NOTLOGIN",
				"code": 0,
			})
		}
	}
}
